#include "energy_sampling.h"

static void PowerSamplingDecode(CANInstance *sampling_can)
{
	static float t=0;
    int16_t tmp=0;
	uint8_t* rxbuff = sampling_can->rx_buff;
    Power_Sampling_Instance *power_sampling = (Power_Sampling_Instance *)sampling_can->id;
    Power_Data_Measure_s *measure =&(power_sampling->measure);
	DaemonReload(power_sampling->daemon);
	/* 解析电流值 (第1-2字节) */
	tmp = (int16_t)((rxbuff[0] << 8) | rxbuff[1]);

	measure->current = (float)tmp / CURRENT_SCALE_FACTOR; /* 转换为A */
	
	/* 解析电压值 (第3-4字节) */
	tmp = (int16_t)((rxbuff[2] << 8) | rxbuff[3]);
	measure->voltage = (float)tmp / VOLTAGE_SCALE_FACTOR; /* 转换为V */
	
	/* 解析功率值 (第5-6字节) */
	tmp = (int16_t)((rxbuff[4] << 8) | rxbuff[5]);
	measure->power = (float)tmp / POWER_SCALE_FACTOR; /* 转换为W */
	
	/* 解析汇报时间间隔 (第7字节) */
	measure->report_interval = rxbuff[6];

	measure->dt=DWT_GetTimeline_ms()-t;
	t=DWT_GetTimeline_ms();
	/* 第8字节为保留字节，忽略 */
}
/*
* @brief 功率采样模块初始化函数
* @todo 
*/
/*	
* @brief 功率采样模块丢失回调函数，目前只有第七位有意义，代表期望的回传频率，单位为ms，0为不回传,注意，由于硬件问题，采样速率最低为2ms，且最好为2的倍数
*/
void PowerSamplingLostCallback(void *owner)
{
	Power_Sampling_Instance *power_sampling = (Power_Sampling_Instance *)owner;
	uint8_t txbuff[8] = {0,0,0,0,0,0,4,0};
	for(int i = 0;i<8;i++)
	{
		power_sampling->sampling_can->tx_buff[i] = txbuff[i];
	}
	CANTransmit(power_sampling->sampling_can ,3);
}
Power_Sampling_Instance *PowerSamplingInit(Power_Sampling_Init_Config_s *config)
{
    Power_Sampling_Instance *power_sampling = (Power_Sampling_Instance *)malloc(sizeof(Power_Sampling_Instance));
    memset(power_sampling, 0, sizeof(Power_Sampling_Instance));

    config->can_init_config.can_module_callback = PowerSamplingDecode;
    config->can_init_config.id = power_sampling;
    power_sampling->sampling_can = CANRegister(&config->can_init_config);
	Daemon_Init_Config_s conf = {
		.callback = PowerSamplingLostCallback,
		.owner_id = power_sampling,
		.reload_count = 10,
	};
	power_sampling->daemon =DaemonRegister(&conf);
	return power_sampling;
}

